const { Account } = require('../models/Middle')
const { Op } = require('sequelize')
const moment = require('moment')
const seq = require('../utils/seq')
const AppRes = require('../config/app.res')

// 新增
async function add (account) {
  account.ctime = moment().format('YYYY-MM-DD HH:mm:ss')
  account.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  try {
    return await Account.create(account)
  } catch (error) {
    throw error
  }
}

// 查询（分页、排序、模糊查询搜索、查询状态）
/**
 * limit 提取多少行，offset 跳过多少行
 * @param {*} page 当前页码
 * @param {*} size 每页条数
 */
async function findAll (query, uid) {
  try {
    const size = query.size ? parseInt(query.size) : 10 // 如果没传参数设置一个默认值
    const page = query.page ? parseInt(query.page) : 1
    const { count, rows } = await Account.findAndCountAll({
      include: {
        all: true
      },
      where: {
        uid,
        type: {
          [Op.like]:  query.type ? `%${JSON.parse(query.type) ? 1 : 0}%` : '%%'
        },
        [Op.or]: [ // 模糊查询
          { money: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { pay: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { ptime: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { location: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { tag: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { remark: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { ctime: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { mtime: { [Op.like]: query.search ? `%${query.search}%` : '%%' } }
        ],
      },
      offset: (page - 1) * size,
      limit: size,
      distinct: true, // 避免分页出的总数和实际数不匹配
      order: [
        [query.order ? query.order : 'ctime', query.sort ? query.sort : 'desc'] // 使用 Element 表格中的排序是互斥的，所以每次排序只能排一个元素的
      ]
    })
    return {
      count,
      data: rows
    }
  } catch (error) {
    throw error
  }
}

// 修改
async function update (account, uid) {
  account.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  try {
    if (account.uid === uid) {
      return await Account.update(account, {
        where: {
          id: account.id,
          uid
        }
      })
    } else {
      return AppRes['401']
    }
  } catch (error) {
    throw error
  }
}

// 删除
async function deleteById (id, uid) {
  try {
    const res = await Account.findOne({
      where: { id }
    })
    if (res.uid === uid) {
      return await Account.destroy({
        where: {
          id,
          uid
        }
      })
    } else {
      return AppRes['401']
    }
  } catch (error) {
    throw error
  }
}

// 根据id查询
async function findOneById (id) {
  try {
    return await Account.findOne({
      include: {
        all: true
      },
      where: {
        id
      }
    })
  } catch (error) {
    throw error
  }
}

module.exports = {
  add,
  findAll,
  update,
  deleteById,
  findOneById
}